package com.lianda.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider;
import com.alibaba.fastjson.parser.deserializer.FieldTypeResolver;
import com.alibaba.fastjson.serializer.NameFilter;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

//字段名转换
public class FastjsonTest {

    static Map<String, String> keyMap = new HashMap<String, String>(){{
        put("name", "MyName");
        put("age", "MyAge");
        put("kind", "MyKind");
    }};

    static Map<String, String> valueMap = new HashMap<String, String>(){{
        put("cat", "dog");
        put("123", "123dog");
    }};

    public static void main(String[] args) {
        String json = "{\"name\":\"abc\",\"age\":\"123\",\"info\":[{\"message\":\"cat\",\"kind\":\"asd\"},{\"message\":\"cat\",\"kind\":\"dedsf\"}]}";
        ExtraProcessor processor = new MyExtraProcessor();
//        Map<String, Object> map = JSON.parseObject(json, new TypeReference<Map<String, Object>>(){}.getType(), new MyFieldTypeResolver());
        User user = JSON.parseObject(json, User.class, new MyExtraProcessor());
//        System.out.println("========" + JSON.toJSONString(map, new SimpleNameFilter()));
        System.out.println("===============");
    }

    //序列化（转为字符串）时执行
    static class SimpleNameFilter implements NameFilter {
        @Override
        public String process(Object object, String name, Object value) {
            String newName = keyMap.get(name);
            if (newName != null && !newName.equals("")) {
                return newName;
            }
            return name;
        }
    }

    //只能pojo类用
    static class MyExtraProcessor implements ExtraProcessor, ExtraTypeProvider {
        @Override
        public void processExtra(Object object, String key, Object value) {
            String newName = keyMap.get(key);
            if (newName != null && !newName.equals("")) {
                System.out.println("===");
            }
        }

        @Override
        public Type getExtraType(Object object, String key) {
            if ("value".equals(key)) {
                return int.class;
            }
            return null;
        }
    }

    static class MyFieldTypeResolver implements FieldTypeResolver {
        @Override
        public Type resolve(Object object, String fieldName) {
            System.out.println("====");
            return null;
        }
    }
}
